<script setup>
import { KeyOutlined, LogoutOutlined, ProfileOutlined, UserOutlined } from '@ant-design/icons-vue'
import { updatePwd } from '~@/api/system/index'

const props = defineProps({
  visible: {
    type: Boolean,
    required: false,
  },
  type: {
    type: String,
    default: 'add',
    required: false,
  },
  id: {
    type: [Number, String],
    default: 0,
    required: false,
  },
})
const emits = defineEmits(['update:modelValue'])
const message = useMessage()
const userStore = useUserStore()
const multiTabStore = useMultiTab()
const layoutMenuStore = useLayoutMenu()
const router = useRouter()
const { avatar, username, userId } = storeToRefs(userStore)
const passwordForm = ref()
const menuForm = ref()
const form = reactive({
  userId,
  oldPwd: '',
  newPwd: '',
  confirmPass: '',
})
const visible1 = ref(true)
const locaVisible = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  },
})

const titleMap = {
  add: '新增菜单',
  edit: '编辑菜单',
  children: '新增子菜单',
}
const loading = ref(false)
const menuData = shallowRef([])
const rules = computed(() => {
  return {
    oldPwd: [
      { required: true, message: '请输入旧密码', trigger: 'change' },
    ],
    newPwd: [
      { required: true, message: '请输入新密码', trigger: 'change' },
      { min: 6, message: '密码长度不能少于6位', trigger: 'blur' },
    ],
    confirmPass: [
      {
        required: true, // ✅ 用来显示 *，不单独触发校验
        message: '',
        trigger: 'change',
      },
      {
        validator: (rule, value) => {
          if (!value) {
            return Promise.reject('请确认密码')
          }
          if (value !== formState.newPwd) {
            return Promise.reject('两次输入的密码不一致')
          }
          return Promise.resolve()
        },
        trigger: ['blur', 'change'],
      },

    ],

  }
})
function handleSubmit() {
  loading.value = true
  formRef.value.validateFields()
    .then(() => {
      console.log('Received values of form: ', values)
      //   console.log('formState: ', toRaw(form));
      //   visible.value = false;
      formRef.value.resetFields()
      //   console.log('reset formState: ', toRaw(formState));
    })
    .catch((error) => {
      console.log('error', error)
    })
  // console.log('submit');
  loading.value = false
  // reset();
}
function reset() {
  formRef.value.resetFields()
}
function close() {
  locaVisible.value = false
  reset()
}
async function handleClick({ key }) {
  if (key === 'logout') {
    const hide = message.loading('退出登录...', 0)
    try {
      await userStore.logout()
    }
    finally {
      hide()
      // message.success('退出登录成功', 3)
      router.push({
        path: '/login',
      }).then(() => {
        multiTabStore.clear()
        layoutMenuStore.clear()
      })
    }
  }
  else {
    resetPassword()
    // const hide = message.loading('退出登录...', 0)
  }
}
// 打开修改密码弹窗
function resetPassword(record) {
  if (passwordForm.value) {
    passwordForm.value.resetFields()
  }
  passwordOpen.value = true
}
// 确认修改密码
async function handleOk() {
  try {
    await passwordForm.value.validate()
    // const params = {
    //   userId,
    //   oldPwd: Secret.encrypt(formState.oldPwd),
    //   newPwd: Secret.encrypt(formState.newPwd),
    // }
    // console.log(params)
    formState.oldPwd = Secret.encrypt(formState.oldPwd)
    formState.newPwd = Secret.encrypt(formState.newPwd)
    formState.confirmPass = Secret.encrypt(formState.confirmPass)
    const { data } = await updatePwd(formState)
    console.log(data)
    message.success('修改成功')
    passwordOpen.value = false
  }
  catch (error) {
    // message.error('请检查表单填写是否正确')
  }
}
</script>

<template>
  <!-- 添加菜单 -->
  <a-modal v-model:open="visible1" :title="menuTitle" :get-container="false" width="800px">
    <template #footer>
      <a-button key="back" @click="close">
        取消
      </a-button>
      <a-button key="submit" type="primary" :loading="loading" @click="handleSubmit">
        确定
      </a-button>
    </template>
    {{ visible }}
    <a-form ref="menuForm" :model="form">
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item
            label="菜单名称" name="name" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
            :rules="[{ required: true, message: '请输入菜单名称!' }]"
          >
            <a-input v-model:value="form.name" placeholder="请输入菜单名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="菜单状态" name="status" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-radio-group v-model:value="form.status" name="radioGroup">
              <a-radio :value="1">
                启用
              </a-radio>
              <a-radio :value="0">
                禁用
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item
            label="路由名称" name="routerName" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
            :rules="[{ required: true, message: '路由名称!' }]"
          >
            <a-input v-model:value="form.routerName" placeholder="请输入路由名称" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item
            label="路由路径" name="routerPath" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }"
            :rules="[{ required: true, message: '路由路径!' }]"
          >
            <a-input v-model:value="form.routerPath" placeholder="请输入路由路径" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="菜单排序" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-input-number v-model:value="form.order" :min="0" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="菜单图标" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-input v-model:value="form.routerPath" placeholder="菜单图标" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="24">
        <a-col :span="12">
          <a-form-item label="父级菜单" name="parent" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-cascader v-model:value="form.parent" :default-value="[0]" :field-names="{ label: 'label', value: 'value', children: 'children' }" :options="menuData" placeholder="Please select" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="隐藏菜单" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
            <a-radio-group v-model:value="form.hidden" name="radioGroup">
              <a-radio :value="1">
                显示
              </a-radio>
              <a-radio :value="0">
                隐藏
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
